<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
             label-width="120px">
      <el-form-item label="供应商名称" prop="supplierId">
        <el-select v-model="queryParams.supplierId" placeholder="请选择供应商" filterable remote reserve-keyword
                   clearable
                   :remote-method="searchSupplier" :loading="loadingSupplier" style="width: 240px;">
          <el-option v-for="item in optionsSupplier"
                     :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="发生日期" prop="occurDate">
        <el-date-picker v-model="dateRange"
                        style="display: flex;"
                        value-format="yyyy-MM-dd"
                        type="daterange"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="发票序号" prop="invoiceNos">
        <el-input v-model="queryParams.invoiceNos" placeholder="请输入编号"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="发票编号" prop="invoiceCode">
        <el-input v-model="queryParams.invoiceCode" placeholder="请输入发票编号"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>

      <el-form-item label="打款编号" prop="payRecordNo">
        <el-input v-model="queryParams.payRecordNo" placeholder="请输入打款记录编号"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="warning" plain icon="el-icon-download" size="mini"
                   @click="handleExport" v-hasPermi="['develop:FinanceAp:export']">导出
        </el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange" ref="table"
              show-summary :summary-method="getSummaries" :max-height="tableMaxHeight">
      <el-table-column label="编号" align="center" prop="nos"/>
      <el-table-column label="类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ap_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="供应商名称" align="center" prop="supplierName"/>
      <el-table-column label="发生日期" align="center" prop="occurDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.occurDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="期初应付" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.payMoney>0">{{ accSub(scope.row.remainMoney,scope.row.payMoney) }}</span>
          <span v-if="scope.row.paidMoney>0">{{ accAdd(scope.row.remainMoney,scope.row.paidMoney) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="本期应付" align="center" prop="payMoney"/>
      <el-table-column label="本期已付" align="center" prop="paidMoney"/>
      <el-table-column label="期末应付" align="center" prop="remainMoney"/>


      <el-table-column sortable align="center" label="入库编号" prop="storeInNos">
        <template slot-scope="scope">
          <el-tooltip class="item" content="入库详情" effect="dark" placement="left-start">
            <span @click="handleStoreDetail(scope.row)" style="color: #00afff;cursor:pointer;">
              {{ scope.row.storeInNos }}</span>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column label="入库时间" align="center" prop="storeInDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.storeInDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column sortable align="center" label="打款编号" prop="payRecordNo">
        <template slot-scope="scope">
          <el-tooltip class="item" content="打款详情" effect="dark" placement="left-start">
            <span @click="handlePayRecordDetail(scope.row)" style="color: #00afff;cursor:pointer;">
              {{ scope.row.payRecordNo }}</span>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column label="打款时间" align="center" prop="payRecordDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.payRecordDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" @pagination="getList"/>
    <financeAp-form ref="form" @ok="getList"></financeAp-form>
    <finance-buy-invoice-detail ref="invoiceDetail"></finance-buy-invoice-detail>
    <ruku-mingxi-list ref="rukuMingxiList"></ruku-mingxi-list>
    <pay-record-detail ref="payRecorddetail" @ok="getList"></pay-record-detail>
  </div>
</template>

<script>
import {accAdd, accSub, deleteAction, downloadFile, getAction, isEmpty} from '@/api/manage'
import FinanceApForm from '@/views/develop/finance/financeAp/module/FinanceApForm'
import FinanceBuyInvoiceDetail from "@/views/develop/finance/financeBuyInvoice/module/FinanceBuyInvoiceDetail.vue";
import RukuMingxiList from "@/views/develop/lvRuku/module/RukuMingxiList.vue";
import PayRecordDetail from "@/views/develop/payRecord/module/PayRecordDetail.vue";

export default {
  name: "FinanceApList",
  dicts: ['ap_type'],
  components: {
    PayRecordDetail,
    RukuMingxiList,
    FinanceBuyInvoiceDetail,
    FinanceApForm,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 应付账单表格数据
      dataList: [],
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        supplierId: null,
        supplierName: null,
        occurDate: null,
        dueDate: null,
        payMoney: null,
        paidMoney: null,
        remainMoney: null,
        status: null,
        invoiceId: null,
        invoiceNos: null,
        invoiceCode: null,
        payRecordId: null,
        payRecordNo: null,
        description: null,
        orderByColumn: "a.nos",
        isAsc: "asc"
      },
      url: {
        list: '/financeAp/financeAp/list',
        remove: '/financeAp/financeAp/',
        export: '/financeAp/financeAp/export',
      },
      tableMaxHeight: window.innerHeight - 320,
      optionsSupplier: [],
      loadingSupplier: false,
    };
  },
  created() {
    this.getList();
    window.addEventListener('resize', this.getTableHeight);
  },
  destroyed() {
    window.removeEventListener('resize', this.getTableHeight)
  },
  methods: {
    accSub,
    accAdd,
    /** 查询应付账单列表 */
    getList() {
      this.loading = true;
      this.addDateRange(this.queryParams, this.dateRange, "OccurDate")
      getAction(this.url.list, this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getTableHeight() {
      this.tableHeight = window.innerHeight - 320
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$refs.form.handleAdd();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$refs.form.handleUpdate(row);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      deleteAction(this.url.remove, ids).then(response => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      // 先选择供应商
      if (isEmpty(this.queryParams.supplierId)) {
        this.$modal.msgError("请先选择供应商");
        return;
      }
      downloadFile(this.url.export, this.queryParams);
    },


    handleInvoiceDetail(row) {
      this.$refs.invoiceDetail.handleShowByAp(row);
    },

    handleStoreDetail(row) {
      this.$refs.rukuMingxiList.showByRukuId(row.storeInId);
    },

    handlePayRecordDetail(row) {
      if (isEmpty(row.payRecordId)) {
        this.$modal.msgError("该应付账单未关联付款记录");
      } else {
        this.$refs.payRecorddetail.showDetailByRecordId(row.payRecordId);
      }
    },

    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (column.property === "payMoney"
          || column.property === 'paidMoney'
        ) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return accAdd(prev, curr);
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    },

    async searchSupplier(queryString) {
      this.loadingSupplier = true;
      if (queryString) {
        let params = {
          "pageNum": 1,
          "pageSize": 20,
          "name": queryString
        };
        getAction("/goodsSupplier/goodsSupplier/list", params).then(response => {
          this.optionsSupplier = response.rows;
          this.loadingSupplier = false;
        });
      } else {
        this.optionsSupplier = [];
        this.loadingSupplier = false;
      }
    },


  }
};
</script>
